package com.dqx.opengl_es_demo.face;

import android.content.Context;
import android.opengl.GLES20;

import com.dqx.opengl_es_demo.R;
import com.dqx.utils.GLUtils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * 绘制点的工具类
 */
public class GLPoints {
    private FloatBuffer vertexBuffer;
    private int bufferLength = 106 * 2 * 4;
    private int programId = -1;
    private int aPositionHandle;

    private int[] vertexBuffers;
    private Context context;

    public GLPoints(Context context) {
        this.context = context;
        vertexBuffer = ByteBuffer.allocateDirect(bufferLength)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        vertexBuffer.position(0);
    }

    public void init() {
        programId = GLUtils.buildProgram(context, R.raw.point_vertex, R.raw.point_frag);
        aPositionHandle = GLES20.glGetAttribLocation(programId, "aPosition");
        vertexBuffers = new int[1];
        GLES20.glGenBuffers(1, vertexBuffers, 0);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffers[0]);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, bufferLength, vertexBuffer, GLES20.GL_STATIC_DRAW);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }

    public void drawPoints(float[] points) {
        vertexBuffer.rewind();
        vertexBuffer.put(points);
        vertexBuffer.position(0);

        GLES20.glUseProgram(programId);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, vertexBuffers[0]);
        GLES20.glBufferSubData(GLES20.GL_ARRAY_BUFFER, 0, bufferLength, vertexBuffer);
        GLES20.glEnableVertexAttribArray(aPositionHandle);
        GLES20.glVertexAttribPointer(aPositionHandle, 2, GLES20.GL_FLOAT, false,
                0, 0);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
        GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 106);
    }

    public void release() {
        GLES20.glDeleteProgram(programId);
        GLES20.glDeleteBuffers(1, vertexBuffers, 0);
    }
}
